<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.partSetting.CategoryProperty')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="500"
      :width="1000"
    >
      <BasicTable @register="registerTable">
        <!-- 选择属性 -->
        <template #isSelect="{ record }">
          <Checkbox v-model:checked="record.isSelect" @change="changeIsSelect(record)" />
        </template>
        <!-- 是否为敏感属性 -->
        <template #isOnly="{ record }">
          {{ record.isOnly ? t('common.yes') : t('common.no') }}
        </template>
        <!-- 是否为系统分类属性 -->
        <template #isSystem="{ record }">
          {{ record.isSystem ? t('common.yes') : t('common.no') }}
        </template>
        <!-- 操作 -->
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                // 修改
                icon: 'ant-design:edit-outlined',
                tooltip: t('common.edit'),
                onClick: handleEdit.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </BasicModal>
    <!-- 类属性弹窗 -->
    <PartClassPropModal @register="registerClassPropertyModal" @success="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Checkbox } from 'ant-design-vue';
  import {
    getPartClassPropertyList,
    updatePartClassPropertyList,
    UpdatePartTypePropSingle,
  } from '/@/api/demo/system';
  import { TypePropColumns } from './data';

  import PartClassPropModal from './partClassPropModal.vue';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const PartId = ref('');

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    const { partid } = data;
    PartId.value = partid;
  });

  // 初始化表格
  const [registerTable, { updateTableDataRecord, getDataSource, reload }] = useTable({
    api: getPartClassPropertyList,
    beforeFetch: (params) => {
      params.partId = PartId.value;
    },
    columns: TypePropColumns(),
    afterFetch: (res) => {
      return res.map((item) => {
        return {
          ...item,
          isSelect: item.isSelect === '1',
        };
      });
    },
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 10, pageSizeOptions: ['10', '20', '30', '40'], defaultPageSize: 10 },
    canResize: true,
    scroll: { y: 450 },
    rowKey: 'prop',
    actionColumn: {
      width: 100,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 类属性弹窗
  const [registerClassPropertyModal, { openModal: openModalClassPropertyModal }] = useModal();

  const handleEdit = (record) => {
    openModalClassPropertyModal(true, {
      isUpdate: true,
      record: record,
      docTypeId: PartId.value, // 判断是否为选择属性，1传递P零件分类id，0传递artRevision
      tableData: getDataSource(),
      type: '零件分类',
    });
  };

  const changeIsSelect = async (record) => {
    const newParams = {
      ...record,
      isSelect: record.isSelect ? '1' : '0',
      docTypeId: PartId.value,
    };
    await UpdatePartTypePropSingle(newParams);
    updateTableDataRecord(record.prop, record);
  };

  async function handleSubmit() {
    const dataSource = getDataSource();

    // 检查是否所有项的 isOnly 都为 false
    if (dataSource.every((item) => item.isOnly === false)) {
      createMessage.warning(t('routes.table.formManagement.sensitivePropertyAtLeastOne'));
      return;
    }

    // 转换 isSelect 和 isOnly 的值
    const updatedDataSource = dataSource.map((item) => ({
      ...item,
      isSelect: item.isSelect ? '1' : '0',
      isOnly: item.isOnly ? '1' : '0',
    }));

    // 更新数据
    updatePartClassPropertyList(PartId.value, updatedDataSource).then((res) => {
      if (res) {
        createMessage.success(t('common.saveSuccess'));
        handleCancel();
      }
    });
  }

  const handleCancel = () => {
    PartId.value = '';
    closeModal();
  };
</script>

<style lang="less" scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }

  ::v-deep(.ant-table-body) {
    height: 500px !important;
  }

  ::v-deep(.ant-table-tbody > tr > td) {
    padding: 10px !important;
  }
</style>
